<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="选择结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:assess:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:assess:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:assess:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:assess:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scaleList" @selection-change="handleSelectionChange" border stripe highlight-current-row class="scale-main-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="120" show-overflow-tooltip />
      <el-table-column label="开始时间" align="center" prop="startTime" min-width="150" />
      <el-table-column label="结束时间" align="center" prop="endTime" min-width="150" />
      <el-table-column label="状态" align="center" min-width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '已开放' ? 'success' : 'info'">
            {{ (new Date(scope.row.startTime) > new Date()) ? '未开放' : '已开放' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否开放" align="center" min-width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isOpen"
            :active-value="'1'"
            :inactive-value="'0'"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="任务内容" align="center" min-width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewScaleDetail(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:assess:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:assess:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改测评任务抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="openDrawer"
      direction="rtl"
      size="70%"
      :before-close="handleDrawerClose"
      append-to-body
      class="scale-drawer"
    >
      <div class="drawer-container">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="scale-form">
              <el-card shadow="hover" class="scale-card">
                <div slot="header" class="card-header">
                  <span>任务基本信息</span>
                </div>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="任务名称" prop="taskName">
                      <el-input v-model="form.taskName" placeholder="请输入任务名称" clearable />
        </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="开放状态" prop="isOpen">
                      <el-switch v-model="form.isOpen" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="开始时间" prop="startTime">
                      <el-date-picker
                        v-model="form.startTime"
                        type="datetime"
                        placeholder="选择开始时间"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 100%"
                      />
        </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束时间" prop="endTime">
                      <el-date-picker
                        v-model="form.endTime"
                        type="datetime"
                        placeholder="选择结束时间"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 100%"
                      />
        </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="区域" prop="openUnit">
                      <el-select v-model="form.openUnit" placeholder="请选择区域" style="width: 100%;" @change="handleOpenUnitChange">
                        <el-option
                          v-for="dict in openUnitOptions"
                          :key="dict.dictValue"
                          :label="dict.dictLabel"
                          :value="dict.dictValue"
                        ></el-option>
                      </el-select>
        </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="开放对象" prop="openTargetArray">
                      <el-checkbox-group v-model="form.openTargetArray">
                        <el-checkbox
                          v-for="dict in openTargetOptions"
                          :key="dict.dictValue"
                          :label="dict.dictValue"
                          :disabled="false"
                        >
                          {{ dict.dictLabel }}
                        </el-checkbox>
                      </el-checkbox-group>
                      <div v-if="form.openTargetArray && form.openTargetArray.length > 0" class="selected-targets">
                        <span>已选: {{ form.openTargetArray.join(', ') }}</span>
                      </div>
        </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20" v-if="form.openUnit">
                  <el-col :span="24">
                    <el-form-item :label="getAreaLabel()" :prop="form.openUnit === '7' ? 'userIds' : 'areaIds'">
                      <!-- 区域选择 (学校/年级/班级) - 使用树形控件 -->
                      <div v-if="form.openUnit !== '7'" class="area-tree-container">
                        <el-input
                          v-model="areaFilterText"
                          placeholder="输入关键字进行过滤"
                          clearable
                          style="margin-bottom: 8px;"
                        ></el-input>
                        <el-tree
                          ref="areaTree"
                          :data="areaOptions"
                          :props="{
                            label: 'deptName',
                            children: 'children'
                          }"
                          node-key="deptId"
                          :filter-node-method="filterAreaNode"
                          show-checkbox
                          default-expand-all
                          highlight-current
                          :check-strictly="true"
                          @check="handleAreaTreeCheck"
                          class="area-selection-tree"
                        >
                          <span class="custom-tree-node" slot-scope="{ node, data }">
                            <span>{{ node.label }}</span>
                            <span v-if="data.type === 6" class="node-tag">
                              <el-tag size="mini" type="success">可选</el-tag>
                            </span>
                          </span>
                        </el-tree>
                        
                        <div v-if="form.areaIds && form.areaIds.length > 0" class="selected-areas">
                          <div class="selected-areas-title">已选择的班级:</div>
                          <el-tag
                            v-for="id in form.areaIds"
                            :key="id"
                            closable
                            @close="removeSelectedArea(id)"
                            type="primary"
                            effect="plain"
                            size="small"
                            style="margin: 4px;"
                          >
                            {{ getAreaNameById(id) }}
                          </el-tag>
                        </div>
                      </div>
                      
                      <!-- 个人模式 - 人员选择 -->
                      <div v-else>
                        <!-- 两种选择模式切换 -->
                        <el-radio-group v-model="personalSelectionMode" style="margin-bottom: 10px;">
                          <el-radio label="class">按班级选择</el-radio>
                          <el-radio label="user">按人员选择</el-radio>
                        </el-radio-group>
                        
                        <!-- 按班级选择 - 与班级模式相同的树形控件 -->
                        <div v-if="personalSelectionMode === 'class'" class="area-tree-container">
                          <el-input
                            v-model="areaFilterText"
                            placeholder="输入关键字进行过滤"
                            clearable
                            style="margin-bottom: 8px;"
                          ></el-input>
                          <el-tree
                            ref="areaTree"
                            :data="areaOptions"
                            :props="{
                              label: 'deptName',
                              children: 'children'
                            }"
                            node-key="deptId"
                            :filter-node-method="filterAreaNode"
                            show-checkbox
                            default-expand-all
                            highlight-current
                            :check-strictly="true"
                            @check="handleAreaTreeCheck"
                            class="area-selection-tree"
                          >
                            <span class="custom-tree-node" slot-scope="{ node, data }">
                              <span>{{ node.label }}</span>
                              <span v-if="data.type === 6" class="node-tag">
                                <el-tag size="mini" type="success">可选</el-tag>
                              </span>
                            </span>
                          </el-tree>
                          
                          <div v-if="form.areaIds && form.areaIds.length > 0" class="selected-areas">
                            <div class="selected-areas-title">已选择的班级:</div>
                            <el-tag
                              v-for="id in form.areaIds"
                              :key="id"
                              closable
                              @close="removeSelectedArea(id)"
                              type="primary"
                              effect="plain"
                              size="small"
                              style="margin: 4px;"
                            >
                              {{ getAreaNameById(id) }}
                            </el-tag>
                          </div>
                        </div>
                        
                        <!-- 按人员选择 - 使用人员选择对话框 -->
                        <div v-else>
                          <el-input
                            placeholder="点击选择人员"
                            v-model="selectedUserNames"
                            readonly
                            @click.native="openUserSelectDialog"
                            clearable
                            style="width: 100%"
                          >
                            <el-button slot="append" icon="el-icon-user" @click="openUserSelectDialog"></el-button>
                          </el-input>
                          
                          <div v-if="form.userIds && form.userIds.length > 0" class="selected-users">
                            <div class="selected-users-title">已选择的人员:</div>
                            <el-tag
                              v-for="user in selectedUsers"
                              :key="user.userId"
                              closable
                              @close="removeSelectedUser(user.userId)"
                              type="primary"
                              effect="plain"
                              size="small"
                              style="margin: 4px;"
                            >
                              {{ user.userName }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
        </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="量表选择" name="scales">
            <el-card shadow="hover" class="scale-card">
              <div slot="header" class="card-header">
                <span>选择量表</span>
                <span class="required-hint">*必选</span>
              </div>
              <el-alert
                v-if="!form.scaleIds || form.scaleIds.length === 0"
                title="请至少选择一个量表"
                type="warning"
                show-icon
                :closable="false"
                style="margin-bottom: 15px;"
              />
              <el-transfer
                v-model="form.scaleIds"
                :data="scaleOptions"
                :titles="['可选量表', '已选量表']"
                :props="{
                  key: 'id',
                  label: 'name'
                }"
                filterable
                filter-placeholder="请输入量表名称"
              >
              </el-transfer>
              <div v-if="form.scaleIds && form.scaleIds.length > 0" class="selected-scales">
                <h4>已选量表 ({{ form.scaleIds.length }}个):</h4>
                <div v-for="(id, index) in form.scaleIds" :key="'selected_' + id + '_' + index" class="selected-scale-item">
                  {{ getScaleName(id) }}
                </div>
              </div>
              <div v-else class="no-scales-selected">
                请至少选择一个量表
              </div>
            </el-card>
          </el-tab-pane>
          
          <!-- <el-tab-pane label="其他设置" name="settings">
            <el-card shadow="hover" class="scale-card">
              <div slot="header" class="card-header">
                <span>其他设置</span>
              </div>
              <el-form ref="settingsForm" label-width="120px">
                <el-form-item label="填写说明">
                  <el-input 
                    type="textarea" 
                    v-model="form.description" 
                    :rows="4" 
                    placeholder="请输入填写说明"
                  />
        </el-form-item>
                <el-form-item label="显示结果">
                  <el-switch v-model="form.showResult"></el-switch>
                </el-form-item>
                <el-form-item label="任务备注">
                  <el-input 
                    type="textarea" 
                    v-model="form.remark" 
                    :rows="4" 
                    placeholder="请输入任务备注"
                  />
        </el-form-item>
      </el-form>
            </el-card>
          </el-tab-pane> -->
        </el-tabs>
        <div class="drawer-footer">
          <el-button type="primary" @click="submitForm" icon="el-icon-check">确 定</el-button>
          <el-button @click="closeDrawer" icon="el-icon-close">取 消</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 查看量表详情抽屉 -->
    <el-drawer
      title="查看量表详情"
      :visible.sync="viewOpen"
      direction="rtl"
      size="70%"
      :before-close="handleViewDrawerClose"
      append-to-body
      class="scale-drawer"
    >
      <div class="drawer-container">
        <el-tabs v-model="viewActiveTab" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-card shadow="hover" class="scale-card">
              <div slot="header" class="card-header">
                <span>基本信息</span>
              </div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="量表编号" :span="1">{{ viewForm.id }}</el-descriptions-item>
                <el-descriptions-item label="量表名称" :span="1">{{ viewForm.name }}</el-descriptions-item>
                <el-descriptions-item label="简称" :span="1">{{ viewForm.shortName }}</el-descriptions-item>
                <el-descriptions-item label="指标名称" :span="1">{{ viewForm.evaluation }}</el-descriptions-item>
                <el-descriptions-item label="积分方式" :span="2">
                  {{ viewForm.pointsType === '0' || viewForm.pointsType === 0 ? '总分' : '平均分' }}
                </el-descriptions-item>
                <el-descriptions-item label="指导语" :span="2">{{ viewForm.introduce || '-' }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="测评等级" name="levels">
            <el-card shadow="hover" class="scale-card">
              <div slot="header" class="card-header">
                <span>测评等级列表</span>
              </div>
              <el-table v-if="viewForm.levels && viewForm.levels.length > 0" :data="viewForm.levels" border stripe class="scale-table">
                <el-table-column label="行为名称" prop="name" min-width="120" show-overflow-tooltip />
                <el-table-column label="测评结果描述" prop="description" min-width="180" show-overflow-tooltip />
                <el-table-column label="测评结果等级" prop="level" width="100" align="center" />
                <el-table-column label="最低分" prop="minScore" width="80" align="center" />
                <el-table-column label="能否低于最低分" width="120" align="center">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.canBeLower ? 'success' : 'info'">
                      {{ scope.row.canBeLower ? '是' : '否' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
              <div v-else class="empty-data">
                <i class="el-icon-document"></i>
                <p>暂无测评等级数据</p>
              </div>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="问题和选项" name="questions">
            <el-card shadow="hover" class="scale-card">
              <div slot="header" class="card-header">
                <span>问题列表</span>
              </div>
              <div v-if="viewForm.questions && viewForm.questions.length > 0">
                <div v-for="(question, qIndex) in viewForm.questions" :key="'vq-'+qIndex" class="view-question-item">
                  <div class="question-title">
                    <el-tag type="primary">题目 {{qIndex + 1}}</el-tag>
                    <span class="question-content">{{ question.content }}</span>
                    <el-tag size="small" effect="plain" type="success" v-if="question.type === 'single'" style="margin-left: 10px;">单选题</el-tag>
                    <el-tag size="small" effect="plain" type="warning" v-else-if="question.type === 'multiple'" style="margin-left: 10px;">多选题</el-tag>
                  </div>
                  <el-table v-if="question.options && question.options.length > 0" :data="question.options" border stripe class="scale-table">
                    <el-table-column label="选项序号" width="80" align="center">
                      <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                      </template>
                    </el-table-column>
                    <el-table-column label="选项内容" prop="content" min-width="180">
                      <template slot-scope="scope">
                        <div style="white-space: pre-wrap; line-height: 1.5;">{{ scope.row.content }}</div>
                      </template>
                    </el-table-column>
                    <el-table-column label="分值" prop="score" width="80" align="center" />
                  </el-table>
                  <div v-else class="empty-options">暂无选项数据</div>
                </div>
              </div>
              <div v-else class="empty-data">
                <i class="el-icon-document"></i>
                <p>暂无问题数据</p>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
        <div class="drawer-footer">
          <el-button @click="closeViewDrawer" icon="el-icon-close">关 闭</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 人员选择对话框 -->
    <el-dialog
      title="选择人员"
      :visible.sync="userDialogVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="user-dialog-container">
        <!-- 当前班级提示 -->
        <el-alert
          v-if="form.areaIds && form.areaIds.length > 0"
          type="info"
          :title="'当前仅显示选中班级下的用户: ' + form.areaIds.map(id => getAreaNameById(id)).join(', ')"
          show-icon
          :closable="false"
          style="margin-bottom: 15px;"
        />
        
        <!-- 搜索栏 -->
        <div class="user-search-bar">
          <el-form :inline="true" :model="userQueryParams" size="small">
            <el-form-item label="用户名称">
              <el-input
                v-model="userQueryParams.userName"
                placeholder="请输入用户名称"
                clearable
                @keyup.enter.native="handleUserSearch"
              />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input
                v-model="userQueryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                @keyup.enter.native="handleUserSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleUserSearch">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetUserSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 用户列表 -->
        <el-table
          ref="userTable"
          v-loading="userTableLoading"
          :data="userList"
          border
          @selection-change="handleUserSelectionChange"
          row-key="userId"
          :row-class-name="userTableRowClassName"
        >
          <el-table-column 
            type="selection" 
            width="55" 
            align="center" 
            :reserve-selection="true"
            :selectable="row => true"
          />
          <el-table-column label="用户名称" align="center" prop="userName" min-width="120" show-overflow-tooltip />
          <el-table-column label="用户昵称" align="center" prop="nickName" min-width="120" show-overflow-tooltip />
          <el-table-column label="所属班级" align="center" min-width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.dept && scope.row.dept.deptName">{{ scope.row.dept.deptName }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" align="center" prop="phonenumber" min-width="120" show-overflow-tooltip />
        </el-table>
        
        <!-- 分页 -->
        <pagination
          v-show="userTotal > 0"
          :total="userTotal"
          :page.sync="userQueryParams.pageNum"
          :limit.sync="userQueryParams.pageSize"
          @pagination="handleUserPagination"
        />
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelUserSelection">取 消</el-button>
        <el-button type="primary" @click="confirmUserSelection">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAssess, getAssess, delAssess, addAssess, updateAssess, changeAssessStatus, getDeptTree,changeUpdateAssess } from "@/api/system/assess";
import { listTable as listScales } from "@/api/system/table"; // 从量表管理API中导入
import { listUser, getUser } from "@/api/system/user"; // 导入用户列表
import { listDept } from "@/api/system/dept"; // 导入区域列表
export default {
  name: "Assess",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 量表加载状态
      scaleLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 当前激活的标签页
      activeTab: 'basic',
      // 查看时激活的标签页
      viewActiveTab: 'basic',
      // 总条数
      total: 0,
      // 量表表格数据
      scaleList: [],
      // 量表选项
      scaleOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示抽屉
      openDrawer: false,
      // 是否显示查看抽屉
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        startTime: null,
        endTime: null,
        status: null
      },
      // 用户加载状态
      userLoading: false,
      // 用户选项
      userOptions: [],
      // 区域选项
      areaOptions: [],
      // 人员选择的选项
      personOptions: [],
      // 区域选项
      openUnitOptions: [],
      // 开放对象选项
      openTargetOptions: [],
      // 表单参数
      form: {
        id: null,
        taskName: null,
        scaleIds: [],
        startTime: null,
        endTime: null,
        openTargetArray: [], // 用于复选框绑定
        isOpen: false,
        openUnit: null,
        description: null,
        showResult: true,
        remark: null,
        areaIds: [], // 选中的区域IDs
        userIds: [], // 选中的用户IDs
        personIds: [] // 个人模式下选择的人员IDs
      },
      // 查看表单参数
      viewForm: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        openUnit: [
          { required: true, message: "开放区域不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        scaleIds: [
          { required: true, message: "请至少选择一个量表", trigger: "change" }
        ],
        areaIds: [
          { required: true, message: "请选择区域", trigger: "change", 
            validator: (rule, value, callback) => {
              // 只在非个人模式下验证areaIds
              if (this.form.openUnit && this.form.openUnit !== '6') {
                // 如果areaIds不是数组或为空数组，验证失败
                if (!Array.isArray(this.form.areaIds) || this.form.areaIds.length === 0) {
                  callback(new Error('请选择区域'));
                  return;
                }
              }
              callback(); // 验证通过
            }
          }
        ],
        userIds: [
          { required: true, message: "请选择人员", trigger: "change",
            validator: (rule, value, callback) => {
              // 只在个人模式下验证userIds
              if (this.form.openUnit === '6') {
                // 如果userIds不是数组或为空数组，验证失败
                if (!Array.isArray(this.form.userIds) || this.form.userIds.length === 0) {
                  callback(new Error('请选择人员'));
                  return;
                }
              }
              callback(); // 验证通过
            }
          }
        ]
      },
      // 区域筛选文本
      areaFilterText: '',
      // 人员选择对话框可见性
      userDialogVisible: false,
      // 用户搜索参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
      },
      // 用户数据列表
      userList: [],
      // 用户总数
      userTotal: 0,
      // 用户表格加载状态
      userTableLoading: false,
      // 当前选中的用户列表
      tempSelectedUsers: [],
      // 已选择的用户列表
      selectedUsers: [],
      // 已选择的用户名称列表（用于显示在输入框中）
      selectedUserNames: '',
      // 个人模式下的选择方式（class: 按班级选择, user: 按人员选择）
      personalSelectionMode: 'class',
      // 跳过用户选择变更的标志
      skipSelectionChange: false,
    };
  },
  created() {
    this.getList();
    this.getScaleOptions();
    // 初始化区域选项
    this.openUnitOptions = [
      // { dictLabel: '市级', dictValue: '1' },
      // { dictLabel: '区县', dictValue: '2' },
      // { dictLabel: '教育局', dictValue: '3' },
      { dictLabel: '学校', dictValue: '4' },
      { dictLabel: '年级', dictValue: '5' },
      { dictLabel: '班级', dictValue: '6' },
      { dictLabel: '个人', dictValue: '7' }
    ];
    // 初始化开放对象选项
    this.openTargetOptions = [
      { dictLabel: '教师', dictValue: '教师' },
      { dictLabel: '学生', dictValue: '学生' }
    ];
  },
  methods: {
    /** 查询量表列表 */
    getList() {
      this.loading = true;
      listAssess(this.queryParams).then(response => {
        this.scaleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取量表选项列表 */
    getScaleOptions() {
      listScales({}).then(response => {
        const scales = response.rows || [];
        this.scaleOptions = scales.map(scale => {
          return {
            id: scale.id,
            name: scale.name,
            shortName: scale.shortName,
            // 确保key是字符串类型，避免重复key
            key: scale.id ? 'scale_' + scale.id : 'scale_' + Math.random().toString(36).substring(2, 10)
          };
        });
      });
    },
    /** 根据ID获取量表名称 */
    getScaleName(id) {
      const scale = this.scaleOptions.find(item => item.id === id);
      return scale ? scale.name : '未知量表';
    },
    /** 获取区域树 */
    getDeptTree() {
      // 加载区域树数据
      listDept().then(response => {
        // 处理区域树数据
        const treeData = this.handleTree(response.data, "deptId");
        
        // 根据区域类型处理树数据
        let processedData = [];
        if (this.form.openUnit === '4') {
          // 学校模式：只保留到学校层级（type=4），移除后续层级
          processedData = this.limitTreeDepth(treeData, 4);
        } else if (this.form.openUnit === '5') {
          // 年级模式：只保留到年级层级（type=5），移除后续层级
          processedData = this.limitTreeDepth(treeData, 5);
        } else if (this.form.openUnit === '6' || this.form.openUnit === '7') {
          // 班级模式和个人模式：保留全部层级到班级（type=6）
          processedData = this.limitTreeDepth(treeData, 6);
        } else {
          // 其他情况保留原始数据
          processedData = treeData;
        }
        
        this.areaOptions = processedData;
        console.log('处理后的区域树数据:', this.areaOptions);
        
        // 数据加载完成后，延迟设置选中状态并更新已选择班级显示
        setTimeout(() => {
          if (this.$refs.areaTree && this.form.areaIds && this.form.areaIds.length > 0) {
            this.setTreeCheckedNodes();
            
            // 更新已选择班级显示（触发视图更新）
            this.updateSelectedAreas();
          }
        }, 300);
      }).catch(error => {
        console.error("获取区域数据失败:", error);
        this.areaOptions = [];
      });
    },
    
    /** 限制树的深度，根据节点类型 */
    limitTreeDepth(nodes, maxType) {
      if (!nodes || !Array.isArray(nodes)) return [];
      
      return nodes.map(node => {
        // 创建节点的副本，避免修改原始数据
        const newNode = { ...node };
        
        // 如果当前节点类型大于等于限制类型，移除children
        if (newNode.type >= maxType) {
          newNode.children = [];
          return newNode;
        }
        
        // 否则递归处理子节点
        if (newNode.children && newNode.children.length > 0) {
          newNode.children = this.limitTreeDepth(newNode.children, maxType);
        }
        
        return newNode;
      });
    },
    
    /** 处理区域树节点选中事件 */
    handleAreaTreeCheck(data, checked) {
      const { checkedKeys } = checked;
      
      // 根据openUnit确定应该选择的节点类型
      // 4: 学校, 5: 年级, 6: 班级, 7: 个人(使用班级节点)
      const expectedType = Number(this.form.openUnit === '7' ? '6' : this.form.openUnit);
      
      // 筛选出符合当前选择类型的节点
      const validIds = [];
      
      // 找出所有被选中的节点
      for (const id of checkedKeys) {
        const node = this.findNodeById(this.areaOptions, id);
        if (node && node.type === expectedType) {
          validIds.push(id);
        } else if (node && node.type !== expectedType) {
          // 如果选中了不符合类型的节点，取消选中
          this.$nextTick(() => {
            this.$refs.areaTree.setChecked(id, false, false);
          });
        }
      }
      
      // 更新有效选择
      this.form.areaIds = validIds;
      
      // 如果是个人模式，同步到userIds
      if (this.form.openUnit === '7') {
        // 更新用户查询参数，限制只显示所选班级的用户
        if (this.personalSelectionMode === 'class') {
        // 获取班级信息并生成用户列表
        this.syncClassSelectionsToUsers();
        } else if (this.personalSelectionMode === 'user') {
          // 如果当前是用户选择模式，需要刷新用户列表
          // 用户列表通过getUserList方法本身会处理多个班级ID
          if (this.userDialogVisible) {
            this.getUserList();
          }
        }
      }
      
      console.log('有效的选择:', validIds);
    },
    
    /** 移除已选择的区域 */
    removeSelectedArea(id) {
      // 从选择列表中移除
      this.form.areaIds = this.form.areaIds.filter(item => item !== id);
      
      // 如果是个人模式，也从userIds中移除
      if (this.form.openUnit === '7') {
        this.form.userIds = this.form.userIds.filter(item => item !== id);
      }
      
      // 更新树选中状态
      this.$nextTick(() => {
        this.$refs.areaTree && this.$refs.areaTree.setChecked(id, false, false);
      });
    },
    
    /** 根据ID获取区域名称 */
    getAreaNameById(id) {
      // 尝试从树中查找节点
      const node = this.findNodeById(this.areaOptions, id);
      if (node) return node.deptName;
      
      // 如果在树中没找到，可能是数据还未加载完成，返回ID作为临时显示
      console.log('未找到节点:', id);
      return '班级-' + id;
    },
    
    /** 过滤区域树节点 */
    filterAreaNode(value, data) {
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },

    /** 根据ID查找节点 */
    findNodeById(tree, id) {
      if (!tree || !Array.isArray(tree)) return null;
      
      for (const node of tree) {
        if (node.deptId === id) {
          return node;
        }
        
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      
      return null;
    },

    /** 处理区域变更 */
    handleOpenUnitChange(value) {
      // 清空之前的选择
      this.form.areaIds = [];
      this.form.userIds = [];
      this.selectedUsers = [];
      this.selectedUserNames = '';
      
      // 根据不同的区域类型加载数据
      if (value) {
        // 重新获取并处理区域树数据（所有模式都需要，包括个人模式的按班级选择）
        this.getDeptTree();
      }
    },
    /** 获取区域标签文本 */
    getAreaLabel() {
      const unitLabels = {
        '1': '市',
        '2': '区县',
        '3': '教育局',
        '4': '学校',
        '5': '年级',
        '6': '班级',
        '7': '人员'
      };
      
      return unitLabels[this.form.openUnit] || '区域';
    },

    /** 取消按钮 */
    cancel() {
      this.closeDrawer();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        taskName: null,
        scaleIds: [],
        startTime: null,
        endTime: null,
        openTargetArray: [], // 用于复选框绑定
        isOpen: false,
        openUnit: null,
        description: null,
        showResult: true,
        remark: null,
        areaIds: [], // 选中的区域IDs
        userIds: [], // 选中的用户IDs
        personIds: [] // 个人模式下选择的人员IDs
      };
      this.resetForm("form");
      
      // 确保openTargetArray已创建并响应式
      if (!this.form.openTargetArray) {
        this.$set(this.form, 'openTargetArray', []);
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.activeTab = 'basic';
      this.openDrawer = true;
      this.title = "添加测评任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'basic';
      const id = row.id || this.ids;
      getAssess(id).then(response => {
        this.form = response.data;
        
        // 处理复选框数据
        if (this.form.openTarget) {
          // 如果openTarget是字符串，尝试解析为数组
          if (typeof this.form.openTarget === 'string') {
            try {
              // 解析openTarget为数组并赋值给openTargetArray
              let parsedArray = JSON.parse(this.form.openTarget);
              // 确保值类型匹配
              this.$set(this.form, 'openTargetArray', parsedArray);
              console.log('解析后的openTargetArray:', this.form.openTargetArray);
            } catch (e) {
              console.error('解析openTarget失败:', e);
              // 如果JSON解析失败，尝试使用逗号分隔的字符串方式
              this.$set(this.form, 'openTargetArray', this.form.openTarget.split(','));
            }
          } else if (Array.isArray(this.form.openTarget)) {
            // 如果已经是数组，直接使用
            this.$set(this.form, 'openTargetArray', [...this.form.openTarget]);
          } else {
            this.$set(this.form, 'openTargetArray', []);
          }
        } else {
          this.$set(this.form, 'openTargetArray', []);
        }
        
        // 处理量表IDs，确保是数组类型，并过滤null值
        if (this.form.scaleIds) {
          // 如果是字符串形式，转换为数组
          if (typeof this.form.scaleIds === 'string') {
            try {
              // 尝试解析JSON字符串
              let parsedScaleIds = JSON.parse(this.form.scaleIds);
              
              // 过滤null值并转换为数组
              const filteredScaleIds = Array.isArray(parsedScaleIds) 
                ? parsedScaleIds.filter(id => id !== null && id !== undefined) 
                : (parsedScaleIds !== null && parsedScaleIds !== undefined ? [parsedScaleIds] : []);
              
              this.$set(this.form, 'scaleIds', filteredScaleIds);
              console.log('解析后的scaleIds (已过滤null):', this.form.scaleIds);
            } catch (e) {
              console.error('解析scaleIds失败:', e);
              // 如果解析失败，可能是逗号分隔的字符串
              const scaleIdsArray = this.form.scaleIds.split(',')
                .map(id => {
                  const numId = Number(id);
                  return isNaN(numId) ? id : numId; // 尝试转换为数字
                })
                .filter(id => id !== null && id !== undefined && id !== '');
                
              this.$set(this.form, 'scaleIds', scaleIdsArray);
            }
          } else if (Array.isArray(this.form.scaleIds)) {
            // 如果是数组，过滤null值
            const filteredScaleIds = this.form.scaleIds.filter(id => id !== null && id !== undefined);
            this.$set(this.form, 'scaleIds', filteredScaleIds);
          } else if (this.form.scaleIds !== null && this.form.scaleIds !== undefined) {
            // 不是数组也不是字符串，但有值，转为单元素数组
            this.$set(this.form, 'scaleIds', [this.form.scaleIds]);
          } else {
            // null或undefined值
            this.$set(this.form, 'scaleIds', []);
          }
        } else {
          // 如果没有scaleIds，设置为空数组
          this.$set(this.form, 'scaleIds', []);
        }
        
        // 同样处理scaleIdList，确保数据一致
        if (this.form.scaleIdList) {
          if (Array.isArray(this.form.scaleIdList)) {
            const filteredList = this.form.scaleIdList.filter(id => id !== null && id !== undefined);
            this.$set(this.form, 'scaleIdList', filteredList);
            
            // 如果scaleIds是空的，使用过滤后的scaleIdList
            if (!this.form.scaleIds || this.form.scaleIds.length === 0) {
              this.$set(this.form, 'scaleIds', [...filteredList]);
            }
          }
        }
        
        console.log('设置后的scaleIds (最终):', this.form.scaleIds);
        
        // 处理areaIds，确保是数组类型
        if (this.form.createDept) {
          // 将createDept字符串转换为areaIds数组
          const deptIds = this.form.createDept.split(',')
            .filter(id => id !== null && id !== undefined && id !== '')
            .map(id => id.trim()); // 去除可能的空格
          
          // 打印处理后的areaIds，便于调试
          console.log('处理后的areaIds:', deptIds);
          
          this.$set(this.form, 'areaIds', deptIds);
        } else {
          this.$set(this.form, 'areaIds', []);
        }
        
        // 处理userIds，确保是数组类型
        if (this.form.createUser) {
          // 将createUser字符串转换为userIds数组
          const userIds = this.form.createUser.split(',')
            .filter(id => id !== null && id !== undefined && id !== '');
          this.$set(this.form, 'userIds', userIds);
          
          // 如果是个人模式且有用户数据，设置personIds
          if (this.form.openUnit === '7' && userIds.length > 0) {
            // 设置personIds为带user_前缀的IDs
            const personIds = userIds.map(id => 'user_' + id);
            this.$set(this.form, 'personIds', personIds);
            console.log('设置personIds:', personIds);
            
            // 获取用户信息并设置selectedUsers
            const userPromises = userIds.map(userId => getUser(userId));
            Promise.all(userPromises).then(responses => {
              const users = responses
                .filter(res => res && res.data)
                .map(res => res.data)
                .map(user => ({
                  userId: user.userId,
                  userName: user.userName || user.nickName || ('用户' + user.userId)
                }));
              
              this.selectedUsers = users;
              this.updateSelectedUserNames();
            });
          }
        } else {
          this.$set(this.form, 'userIds', []);
          if (this.form.openUnit === '7') {
            this.$set(this.form, 'personIds', []);
          }
        }
        
        // 转换开关状态
        this.form.isOpen = this.form.isOpen === '1';
        
        // 先打开抽屉，再加载树数据
        this.openDrawer = true;
        this.title = "修改测评任务";
        
        // 如果有选择开放区域，加载相应数据
        if (this.form.openUnit) {
          // 先清空areaOptions确保getDeptTree会触发完整的更新
          this.areaOptions = [];
          // 加载区域树数据
          this.getDeptTree();
        }
      });
    },
    
    /** 设置树节点选中状态 */
    setTreeCheckedNodes() {
      if (!this.$refs.areaTree) return;
      
      const areaIds = this.form.areaIds || [];
      console.log('准备设置树选中状态，选中节点IDs:', areaIds);
      
      // 清空现有选中状态
      this.$refs.areaTree.setCheckedKeys([]);
      
      // 设置新的选中状态
      if (areaIds.length > 0) {
        // 遍历每个ID并单独设置，避免一次性设置多个造成问题
        areaIds.forEach(id => {
          try {
            const numId = typeof id === 'string' ? parseInt(id, 10) : id;
            this.$refs.areaTree.setChecked(numId || id, true, false);
            console.log('设置节点选中:', numId || id);
          } catch (e) {
            console.error('设置节点选中失败:', id, e);
          }
        });
        
        // 手动触发更新已选择的班级显示
        this.updateSelectedAreas();
      }
    },
    
    /** 更新已选择的班级显示 */
    updateSelectedAreas() {
      // 强制刷新已选择班级的显示
      if (this.form.areaIds && this.form.areaIds.length > 0) {
        console.log('更新已选择班级显示:', this.form.areaIds);
        // 创建副本以触发Vue的响应式更新
        const tempAreaIds = [...this.form.areaIds];
        this.$set(this.form, 'areaIds', []);
        this.$nextTick(() => {
          this.$set(this.form, 'areaIds', tempAreaIds);
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      // 先检查是否选择了量表
      if (!this.form.scaleIds || this.form.scaleIds.length === 0) {
        this.$message.error("请至少选择一个量表");
        this.activeTab = 'scales'; // 自动切换到量表选择标签页
        return;
      }
      
      // 记录当前的开放对象选择，用于调试
      console.log('提交前的openTargetArray:', this.form.openTargetArray);
      
      // 创建提交表单对象
      const submitForm = { ...this.form };
      
      // 先进行数据预处理
      if (this.form.openUnit === '7') {
        if (this.personalSelectionMode === 'class') {
          // 班级选择模式 - 使用areaIds
          // 将createDept设为选中的班级
          submitForm.createDept = this.form.areaIds.join(',');
          // 个人模式也需要设置createUser，将areaIds同步到userIds
          submitForm.createUser = this.form.areaIds.join(',');
        } else {
          // 人员选择模式 - 使用userIds
          submitForm.createUser = this.form.userIds.join(',');
          submitForm.createDept = ''; // 个人模式不需要区域
          delete submitForm.createDept;
        }
      } else {
        // 区域模式 - 区域IDs作为createDept，逗号分隔的字符串
        // 确保areaIds是数组且有值
        const areaIds = Array.isArray(this.form.areaIds) ? this.form.areaIds : [];
        submitForm.createDept = areaIds.join(',');
        submitForm.createUser = ''; // 区域模式不需要用户
        delete submitForm.createUser;
      }
      
      // 正式验证表单
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将openTargetArray数组直接作为openTargetList传递
          if (Array.isArray(submitForm.openTargetArray) && submitForm.openTargetArray.length > 0) {
            submitForm.openTargetList = submitForm.openTargetArray;
          } else {
            submitForm.openTargetList = [];
          }
          
          // 确保scaleIds正确提交 - 使用scaleIdList字段，并过滤null值
          if (Array.isArray(submitForm.scaleIds) && submitForm.scaleIds.length > 0) {
            // 过滤掉null值
            const filteredScaleIds = submitForm.scaleIds.filter(id => id !== null && id !== undefined);
            submitForm.scaleIdList = [...filteredScaleIds]; // 创建副本防止引用问题
          } else {
            submitForm.scaleIdList = [];
          }
          
          // 转换开关状态为字符串
          submitForm.isOpen = submitForm.isOpen ? '1' : '0';
          
          // 移除不需要提交的字段
          delete submitForm.openTargetArray;
          delete submitForm.personIds;
          delete submitForm.userIds;
          delete submitForm.areaIds;
          // 不再需要scaleIds字段，只使用scaleIdList
          delete submitForm.scaleIds;
          // openTarget会设置为openTargetList
          delete submitForm.openTarget;
          
          console.log('提交表单数据:', submitForm);

          if (submitForm.id != null) {
            updateAssess(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openDrawer = false;
              this.getList();
            });
          } else {
            addAssess(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openDrawer = false;
              this.getList();
            });
          }
        } else {
          // 验证失败时，切换到基本信息标签页
          this.activeTab = 'basic';
          return false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除测评任务编号为"' + ids + '"的数据项？').then(function() {
        return delAssess(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 开关状态改变 */
    handleStatusChange(row) {
      const text = row.isOpen === '1' ? '启用' : '停用';
      this.$modal.confirm('确认要' + text + '该测评任务吗？').then(function() {
        return changeUpdateAssess(row.id,row.isOpen);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(() => {
        row.isOpen = row.isOpen === '1' ? '0' : '1';
      });
    },
    /** 查看量表详情 */
    viewScaleDetail(row) {
      this.viewForm = {};
      this.viewActiveTab = 'basic';
      this.viewForm = { ...row };
      
      // 处理测评等级数据
      if (this.viewForm.taskLevelIds && typeof this.viewForm.taskLevelIds === 'string') {
        try {
          const parsedLevels = JSON.parse(this.viewForm.taskLevelIds);
          this.viewForm.levels = parsedLevels.map(level => {
            return {
              name: level.name || '',
              description: level.detail || '',
              level: level.level || '',
              minScore: level.lowestScore || 0,
              canBeLower: level.isLowestScore || false
            };
          });
        } catch (e) {
          console.error('解析测评等级数据失败', e);
          this.viewForm.levels = [];
        }
      } else {
        this.viewForm.levels = [];
      }
      
      // 处理问题选项数据
      if (this.viewForm.questionIds && typeof this.viewForm.questionIds === 'string') {
        try {
          const parsedQuestions = JSON.parse(this.viewForm.questionIds);
          this.viewForm.questions = parsedQuestions.map(q => {
            return {
              content: q.name || '',
              type: q.type || 'single',
              options: (q.options || []).filter(o => o && o.name !== undefined).map(o => {
                return {
                  content: o.name || '',
                  score: o.score || 0
                }
              })
            }
          });
        } catch (e) {
          console.error('解析问题选项数据失败', e);
          this.viewForm.questions = [];
        }
      } else {
        this.viewForm.questions = [];
      }
      
      this.viewOpen = true;
    },
    /** 处理抽屉关闭前的询问 */
    handleDrawerClose(done) {
      this.$confirm('确认关闭？未保存的内容将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.reset();
        done();
      }).catch(() => {
        // 用户取消关闭，不执行任何操作
      });
    },
    /** 处理查看抽屉关闭前的询问 */
    handleViewDrawerClose(done) {
      this.$confirm('确认关闭查看窗口?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        done();
      }).catch(() => {
        // 用户取消关闭，不执行任何操作
      });
    },
    /** 直接关闭编辑抽屉 */
    closeDrawer() {
      this.handleDrawerClose(() => {
        this.openDrawer = false;
      });
    },
    /** 直接关闭查看抽屉 */
    closeViewDrawer() {
      this.handleViewDrawerClose(() => {
        this.viewOpen = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/assess/export', {
        ...this.queryParams
      }, `assess_${new Date().getTime()}.xlsx`)
    },
    /** 打开用户选择对话框 */
    openUserSelectDialog() {
      if (this.form.openUnit !== '7') return;
      
      // 清空临时选择数组，然后重新从已选择的用户列表中复制
      this.tempSelectedUsers = [];
      
      // 确保selectedUsers不为null
      if (this.selectedUsers && this.selectedUsers.length > 0) {
        // 确保用户对象包含必要的字段
        this.tempSelectedUsers = this.selectedUsers.map(user => {
          // 确保返回对象有完整的必要字段
          return {
            userId: user.userId,
            userName: user.userName || ('用户' + user.userId),
            nickName: user.nickName || user.userName || ('用户' + user.userId)
          };
        });
        console.log('打开对话框时设置临时选中状态:', this.tempSelectedUsers.length, '个用户');
      }
      
      // 打开对话框
      this.userDialogVisible = true;
      
      // 不在查询参数中设置deptId，而是直接在getUserList中处理多个班级ID
      delete this.userQueryParams.deptId;
      
      // 加载用户列表
      this.getUserList();
    },
    /** 获取用户列表 */
    getUserList() {
      this.userTableLoading = true;
      
      // 如果没有选择班级，直接正常查询
      if (!this.form.areaIds || this.form.areaIds.length === 0) {
        // 正常查询所有用户
      listUser(this.userQueryParams).then(response => {
          this.processUserResponse(response);
        }).catch(error => {
          console.error('获取用户列表失败:', error);
          this.userTableLoading = false;
        });
        return;
      }
      
      // 对每个班级ID单独查询，然后合并结果
      const selectedAreaIds = [...this.form.areaIds];
      
      // 使用Promise.all和map来并行请求每个班级的用户
      const userPromises = selectedAreaIds.map(deptId => {
        const queryParams = { 
          ...this.userQueryParams,
          deptId: deptId 
        };
        return listUser(queryParams);
      });
      
      Promise.all(userPromises)
        .then(responses => {
          // 合并所有响应的rows
          let allUsers = [];
          let totalUsers = 0;
          
          responses.forEach(response => {
            if (response && response.rows) {
              allUsers = allUsers.concat(response.rows);
              // 累加总数
              totalUsers += (response.total || 0);
            }
          });
          
          // 去重
          const uniqueUsers = [];
          const userMap = {};
          
          allUsers.forEach(user => {
            if (!userMap[user.userId]) {
              userMap[user.userId] = true;
              uniqueUsers.push(user);
            }
          });
          
          // 构造合并后的响应对象
          const mergedResponse = {
            rows: uniqueUsers,
            total: uniqueUsers.length // 使用去重后的数组长度作为总数
          };
          
          // 使用统一的处理方法处理响应
          this.processUserResponse(mergedResponse);
        })
        .catch(error => {
          console.error('获取用户列表失败:', error);
          this.userTableLoading = false;
        });
    },
    /** 处理用户响应数据 */
    processUserResponse(response) {
        // 设置用户数据
        this.userList = response.rows || [];
        this.userTotal = response.total || 0;
        this.userTableLoading = false;
        
      // 延迟一点时间确保表格完全渲染
      setTimeout(() => {
        this.setTableSelection();
      }, 100);
    },
    
    /** 设置表格选中行 */
    setTableSelection() {
      // 确保表格组件存在且已渲染
      if (!this.$refs.userTable) return;
      
      // 阻止handleUserSelectionChange触发
      this.skipSelectionChange = true;
      
            // 先清空选择
            this.$refs.userTable.clearSelection();
            
            // 根据tempSelectedUsers设置选中状态
            if (this.tempSelectedUsers && this.tempSelectedUsers.length > 0) {
        console.log('准备设置选中状态，数量:', this.tempSelectedUsers.length);
        
              // 创建一个查找表，提高效率
              const selectedUserMap = {};
              this.tempSelectedUsers.forEach(user => {
                selectedUserMap[user.userId] = true;
              });
              
              // 对当前页的数据设置选中状态
        let selectedCount = 0;
              this.userList.forEach(row => {
                if (selectedUserMap[row.userId]) {
                  this.$refs.userTable.toggleRowSelection(row, true);
            selectedCount++;
                }
              });
              
        console.log('已设置选中状态，实际选中数量:', selectedCount);
            }
      
      // 延迟恢复handleUserSelectionChange触发
      setTimeout(() => {
        this.skipSelectionChange = false;
      }, 300);
    },
    /** 搜索用户 */
    handleUserSearch() {
      this.userQueryParams.pageNum = 1;
      this.getUserList();
    },
    /** 重置用户搜索 */
    resetUserSearch() {
      // 保存当前的deptId
      const deptId = this.userQueryParams.deptId;
      
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      };
      
      // 恢复deptId
      if (deptId) {
        this.userQueryParams.deptId = deptId;
      }
      
      this.handleUserSearch();
    },
    /** 处理用户表格选择变更 */
    handleUserSelectionChange(selection) {
      // 如果正在通过代码设置选中状态，则跳过处理
      if (this.skipSelectionChange) {
        return;
      }
      
      console.log('选中变更:', selection.length, '个用户');
      
      // 使用深拷贝避免引用问题
      this.tempSelectedUsers = selection.map(user => ({
        userId: user.userId,
        userName: user.userName || user.nickName || ('用户' + user.userId)
      }));
      
      // 输出当前选中的用户信息，便于调试
      console.log('当前选中用户:', this.tempSelectedUsers.map(u => u.userName).join(', '));
    },
    /** 确认用户选择 */
    confirmUserSelection() {
      // 更新已选择的用户列表，确保数据格式一致
      if (this.tempSelectedUsers && this.tempSelectedUsers.length > 0) {
        this.selectedUsers = this.tempSelectedUsers.map(user => ({
          userId: user.userId,
          userName: user.userName || ('用户' + user.userId),
          nickName: user.nickName || user.userName || ('用户' + user.userId)
        }));
      } else {
        this.selectedUsers = [];
      }
      
      // 更新userIds
      this.form.userIds = this.selectedUsers.map(user => user.userId);
      
      // 更新显示在输入框中的用户名称
      this.updateSelectedUserNames();
      
      // 如果是个人模式，同步用户选择到班级选择
      if (this.form.openUnit === '7' && this.personalSelectionMode === 'user') {
        this.syncUserSelectionToClasses();
      }
      
      // 关闭对话框
      this.userDialogVisible = false;
    },
    /** 将班级选择同步到用户选择 */
    syncClassSelectionsToUsers() {
      // 检查是否有班级选择
      if (!this.form.areaIds || this.form.areaIds.length === 0) {
        // 清空用户选择
        this.selectedUsers = [];
        this.form.userIds = [];
        this.selectedUserNames = '';
        return;
      }
      
      // 保存当前选中状态
      const selectedAreaIds = [...this.form.areaIds];
      
      // 加载所有选中班级的用户 - 每个班级单独请求
      const loadUsersPromises = selectedAreaIds.map(classId => {
        return new Promise((resolve) => {
          // 确保传入的是单个班级ID
          listUser({ deptId: classId }).then(response => {
            resolve(response.rows || []);
          }).catch(() => {
            resolve([]);
          });
        });
      });
      
      // 等待所有请求完成
      Promise.all(loadUsersPromises).then(userLists => {
        // 合并所有用户列表
        let allUsers = [];
        userLists.forEach(users => {
          allUsers = allUsers.concat(users);
        });
        
        // 去重
        const uniqueUsers = [];
        const userIdMap = {};
        
        allUsers.forEach(user => {
          if (!userIdMap[user.userId]) {
            userIdMap[user.userId] = true;
            uniqueUsers.push({
              userId: user.userId,
              userName: user.userName || user.nickName || ('用户' + user.userId)
            });
          }
        });
        
        // 更新选中的用户
        this.selectedUsers = uniqueUsers;
        this.form.userIds = uniqueUsers.map(user => user.userId);
        
        // 更新显示在输入框中的用户名称
        this.updateSelectedUserNames();
      });
    },
    /** 将用户选择同步到班级选择 */
    syncUserSelectionToClasses() {
      // 检查是否有用户选择
      if (!this.selectedUsers || this.selectedUsers.length === 0) {
        // 清空班级选择
        this.form.areaIds = [];
        return;
      }
      
      // 获取所有选中用户的区域信息
      const userIds = this.selectedUsers.map(user => user.userId);
      
      // 这里应该有一个API来批量获取用户的区域信息
      // 由于示例中没有，我们假设使用一个模拟API或者单独获取每个用户
      const loadUserDeptsPromises = userIds.map(userId => {
        return new Promise((resolve) => {
          // 假设我们有一个API获取用户区域信息
          // getUserDept(userId).then(deptInfo => {
          //   resolve(deptInfo);
          // });
          
          // 由于没有这个API，我们会在这里模拟
          // 实际项目中应该替换为真实API调用
          setTimeout(() => {
            // 模拟数据：假设用户都属于某些区域
            resolve({
              deptId: null // 实际情况下应返回用户的区域ID
            });
          }, 100);
        });
      });
      
      // 等待所有请求完成
      Promise.all(loadUserDeptsPromises).then(deptInfos => {
        // 收集所有的区域ID
        const deptIds = deptInfos
          .filter(info => info && info.deptId)
          .map(info => info.deptId);
        
        // 去重
        const uniqueDeptIds = [...new Set(deptIds)];
        
        // 更新选中的区域
        if (uniqueDeptIds.length > 0) {
          this.form.areaIds = uniqueDeptIds;
        }
        // 即使没有找到区域，也保留用户选择
      });
    },
    /** 移除已选择的用户 */
    removeSelectedUser(userId) {
      // 从selectedUsers中移除
      this.selectedUsers = this.selectedUsers.filter(user => user.userId !== userId);
      
      // 更新form.userIds
      this.form.userIds = this.selectedUsers.map(user => user.userId);
      
      // 更新显示在输入框中的用户名称
      this.updateSelectedUserNames();
    },
    /** 更新用户名称显示 */
    updateSelectedUserNames() {
      if (this.selectedUsers && this.selectedUsers.length > 0) {
        // 如果用户数量少于3个，显示全部名称
        if (this.selectedUsers.length <= 3) {
          this.selectedUserNames = this.selectedUsers.map(user => user.userName).join(', ');
        } else {
          // 如果用户数量超过3个，显示前3个名称和总数
          this.selectedUserNames = this.selectedUsers.slice(0, 3).map(user => user.userName).join(', ') 
            + ` 等${this.selectedUsers.length}人`;
        }
      } else {
        this.selectedUserNames = '';
      }
    },
    /** 检查用户是否已选中 */
    isUserSelected(row) {
      // 从tempSelectedUsers检查用户是否选中
      const isTemp = this.tempSelectedUsers.some(user => user.userId === row.userId);
      // 从selectedUsers也检查，确保两种状态都被考虑
      const isSelected = this.selectedUsers.some(user => user.userId === row.userId);
      return isTemp || isSelected;
    },
    /** 获取用户表格行的类名 */
    userTableRowClassName({row}) {
      // 根据是否选中返回不同的类名
      return this.isUserSelected(row) ? 'selected-row' : '';
    },
    /** 处理用户分页 */
    handleUserPagination(pageNum, pageSize) {
      this.userQueryParams.pageNum = pageNum;
      this.userQueryParams.pageSize = pageSize;
      this.getUserList();
    },
    /** 取消用户选择 */
    handleCancelUserSelection() {
      // 直接关闭对话框，不更新选择状态
      this.userDialogVisible = false;
    }
  },
  watch: {
    // 监听对话框可见性变化
    userDialogVisible(newVal) {
      if (newVal) {
        // 对话框打开时，延迟一点时间确保表格渲染完成后再设置选中状态
        setTimeout(() => {
          this.setTableSelection();
        }, 300);
      }
    },
    // 监听筛选文本变化
    areaFilterText(val) {
      this.$refs.areaTree && this.$refs.areaTree.filter(val);
    },
    // 监听areaIds变化，更新树选中状态
    'form.areaIds': {
      handler(newVal) {
        this.$nextTick(() => {
          if (this.$refs.areaTree) {
            // 先清除所有选中
            this.$refs.areaTree.setCheckedKeys([]);
            // 设置新的选中项
            if (Array.isArray(newVal) && newVal.length > 0) {
              newVal.forEach(id => {
                this.$refs.areaTree.setChecked(id, true, false);
              });
            }
          }
        });
      },
      deep: true
    },
    // 监听用户列表变化，确保重新设置选中状态
    userList: {
      handler() {
        // 当用户列表数据变化时，延迟一点时间再设置选中状态
        setTimeout(() => {
          if (this.userDialogVisible && this.$refs.userTable) {
            this.setTableSelection();
          }
        }, 100);
      },
      deep: true
    },
    // 监听个人选择模式变化
    personalSelectionMode(newMode) {
      if (this.form.openUnit === '7') {
        if (newMode === 'class') {
          // 从用户选择切换到班级选择
          // 不需要立即同步，因为用户选择更改时已经同步到班级
          // 但确保树显示正确的选中状态
          this.$nextTick(() => {
            if (this.$refs.areaTree && this.form.areaIds.length > 0) {
              this.form.areaIds.forEach(id => {
                this.$refs.areaTree.setChecked(id, true, false);
              });
            }
          });
        } else {
          // 从班级选择切换到用户选择
          // 确保用户选择反映当前班级选择
          if (this.form.areaIds.length > 0) {
            // 如果没有已选用户，同步班级下的用户
            if (this.selectedUsers.length === 0) {
            this.syncClassSelectionsToUsers();
            }
            
            // 更新用户查询参数，限制只显示所选班级的用户
            if (this.userQueryParams) {
              this.userQueryParams.deptId = this.form.areaIds.join(',');
            }
          }
        }
      }
    }
  }
};
</script>

<style scoped>
.selected-scale-item {
  margin: 5px 0;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.scale-card {
  margin-bottom: 20px;
}

.scale-drawer :deep(.el-drawer__header) {
  padding: 15px 20px;
  margin-bottom: 0;
  border-bottom: 1px solid #e8e8e8;
  font-size: 18px;
  font-weight: bold;
}

.scale-drawer :deep(.el-drawer__body) {
  overflow-y: auto;
  padding: 0;
}

.drawer-container {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.drawer-footer {
  margin-top: 20px;
  text-align: center;
}

.empty-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  background-color: #f9f9f9;
}

.empty-data i {
  font-size: 50px;
  margin-bottom: 10px;
}

.empty-options {
  text-align: center;
  padding: 15px;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.selected-scales {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.no-scales-selected {
  text-align: center;
  color: #F56C6C;
  margin-top: 20px;
  padding: 10px;
  background-color: #FEF0F0;
  border-radius: 4px;
  border-left: 3px solid #F56C6C;
}

.view-question-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.question-title {
  margin-bottom: 15px;
  font-size: 14px;
  line-height: 1.5;
  display: flex;
  align-items: center;
}

.question-content {
  margin-left: 10px;
  line-height: 20px;
}

.scale-main-table {
  margin-top: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.scale-form .el-form-item {
  margin-bottom: 18px;
}

.scale-table {
  margin-top: 10px;
}

.dept-node {
  color: #409EFF;
  font-weight: bold;
}

.dept-tag {
  background-color: #F0F9EB;
  color: #67C23A;
  padding: 0 5px;
  border-radius: 4px;
  margin-left: 5px;
  font-size: 12px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 0.7; }
  50% { opacity: 1; }
  100% { opacity: 0.7; }
}

.user-node {
  color: #606266;
}

.help-note {
  margin-bottom: 10px;
  padding: 8px 12px;
  background-color: #ecf8ff;
  border-left: 4px solid #409EFF;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.help-note i {
  margin-right: 8px;
  color: #409EFF;
}

.user-tag {
  background-color: #E6F7FF;
  color: #409EFF;
  padding: 0 5px;
  border-radius: 4px;
  margin-left: 5px;
  font-size: 12px;
}

.empty-node {
  color: #909399;
}

.error-node {
  color: #F56C6C;
}

.area-node {
  color: #409EFF;
}

/* 自定义树节点样式 */
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-action {
  margin-left: 8px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f7ff;
}

/* 非叶子节点的复选框样式 */
:deep(.el-tree-node:not(.is-leaf) > .el-tree-node__content .el-checkbox) {
  opacity: 0.5;
  pointer-events: none;
}

/* 用户节点高亮显示 */
:deep(.el-tree-node.is-user > .el-tree-node__content) {
  color: #67C23A;
}

/* 区域节点样式 */
:deep(.el-tree-node:not(.is-user) > .el-tree-node__content) {
  font-weight: bold;
}

.required-hint {
  color: #F56C6C;
  font-size: 12px;
  margin-left: 5px;
}

/* 确保复选框组可点击 */
:deep(.el-checkbox) {
  pointer-events: auto !important;
  opacity: 1 !important;
}

:deep(.el-checkbox__input) {
  pointer-events: auto !important;
  opacity: 1 !important;
}

:deep(.el-checkbox__label) {
  pointer-events: auto !important;
  opacity: 1 !important;
}

.selected-targets {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
  background-color: #f9f9f9;
  padding: 2px 8px;
  border-radius: 3px;
  border-left: 2px solid #409EFF;
}

.area-tree-container {
  margin-bottom: 20px;
}

.area-selection-tree {
  margin-bottom: 10px;
}

.selected-areas {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.selected-areas-title {
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
}

.user-dialog-container {
  padding: 20px;
}

.user-search-bar {
  margin-bottom: 20px;
}

.selected-users {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.selected-users-title {
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
}

.selected-row {
  background-color: #e6f7ff !important;
  font-weight: bold;
}

.selected-row td {
  background-color: #e6f7ff !important;
}

/* 确保el-table中的checkbox选中状态可见 */
:deep(.el-table__row.selected-row .el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409EFF !important;
  border-color: #409EFF !important;
}
</style>
